package br.com.rapidrest.ioc;

import java.lang.reflect.Field;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;

import br.com.rapidrest.annotation.Inject;
import br.com.rapidrest.annotation.Messages;
import br.com.rapidrest.chain.BasicChainContext;
import br.com.rapidrest.exception.InjectionException;
import br.com.rapidrest.util.LocaleManager;
import br.com.rapidrest.util.MessagesBundle;

public class MessagesFieldHandler implements FieldHandler {

	@Override
	public void handle(Field field, Object target, BasicChainContext context)
			throws InjectionException {
		if (field.isAnnotationPresent(Inject.class)
				&& field.getType().equals(MessagesBundle.class)) {

			try {
				HttpServletRequest request = context.getRequest();
				LocaleManager localeManager = new LocaleManager();
				Locale locale = localeManager.get(request);
				if (locale == null) {
					locale = request.getLocale();
				}
				String baseName = "messages";
				if (field.isAnnotationPresent(Messages.class)) {
					Messages messages = field.getAnnotation(Messages.class);
					baseName = messages.value();
				}
				ResourceBundle bundle = getResourceBundle(baseName, locale);
				MessagesBundle messagesBundle = new MessagesBundle(bundle);
				field.setAccessible(true);
				field.set(target, messagesBundle);
			} catch (IllegalArgumentException e) {
				throw new InjectionException(e);
			} catch (IllegalAccessException e) {
				throw new InjectionException(e);
			}
		}
	}

	protected ResourceBundle getResourceBundle(String baseName, Locale locale) {
		return ResourceBundle.getBundle(baseName, locale);
	}

}